package org.example.security.auth.config.authorize.sso;

import org.example.security.auth.config.authorize.jwt.JwtTokenEnhancer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfigUseSso extends AuthorizationServerConfigurerAdapter {

    @Resource
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManagerBean;

    @Resource
    private UserDetailsService userDetailsService;

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 配置签名使用的密钥，生产环境建议使用非对称加密
        jwtAccessTokenConverter.setSigningKey("jwt_signing_key");
        return jwtAccessTokenConverter;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        // 允许表单认证
        security.allowFormAuthenticationForClients()
                // 检查和获取密钥需要身份认证，使用单点登录时必须配置
                .checkTokenAccess("isAuthenticated()")
                .tokenKeyAccess("isAuthenticated()");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        // 配置JWT的内容增强器，可以在payload中添加自定义数据
        List<TokenEnhancer> delegates = new LinkedList<>();
        delegates.add(new JwtTokenEnhancer());
        delegates.add(jwtAccessTokenConverter());

        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(delegates);

        // 密码模式需要配置
        endpoints.authenticationManager(authenticationManagerBean)
                // jwt token存储策略
                .tokenStore(tokenStore())
                // jwt token 转换器
                .accessTokenConverter(jwtAccessTokenConverter())
                // jwt token 增强器
                .tokenEnhancer(tokenEnhancerChain)
                .reuseRefreshTokens(false)
                .userDetailsService(userDetailsService)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /*
            授权码模式： authorization_code   SSO Client存储令牌，适用于安全性较高的WEB场景
            1、用户：访问资源服务（http://localhost:8081/user/current），跳转到资源服务登陆页面（http://localhost:8081/login）
            2、资源服务：用户未登陆，跳转到授权中心获取授权信息  http://localhost:8080/oauth/authorize?client_id=oauth2-sso-client&redirect_uri=http://localhost:8081/login&response_type=code&state=ZWiBhT
            3、授权中心：用户未登陆，跳转到授权中心的登陆页面 http://localhost:8080/login
            4、用户：输入用户名密码，表单登陆
            5、授权中心：用户登陆成功后跳转到  http://localhost:8080/oauth/authorize?client_id=oauth2-sso-client&redirect_uri=http://localhost:8081/login&response_type=code&state=ZWiBhT
            6、用户：同意授权
            7、授权中心：生成授权码并回调资源服务的redirect_uri（注册时配置，资源服务的登陆地址），并带上code参数（授权码）  http://localhost:8081/login?code=qITF6l&state=ZWiBhT
            8、资源服务：根据注册时的client_id、client_secret和code（授权码）从授权中心获取授权信息 http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=oauth2-sso-client&client_secret=123456&redirect_uri=http://localhost:8081/login&scope=basic&code=qITF6l
            9、资源服务：登陆成功，跳转到资源地址 http://localhost:8081/user/current

            简化模式：implicit   直接将令牌发给客户端，由客户端自行保存令牌，每次请求都需要带上令牌，适用于单页面应用、App
            1、资源服务：发起授权请求  http://localhost:8080/oauth/authorize?response_type=token&client_id=resource-server&redirect_uri=http://localhost:8082/&scope=avatar
            2、用户：登陆授权中心
            3、用户：同意授权
            4、授权中心：生成access_token并回调资源服务的redirect_uri（注册时配置，资源服务的登陆地址），并带上access_token等参数  http://localhost:8082/#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE2MzY1NDI5MzAsImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6IjQyMmQ1NDE2LTNlOTUtNDJhZC05Y2EzLTZiYjNlMDEwZDY0OCIsImNsaWVudF9pZCI6ImNsaWVudCIsImVuaGFuY2UiOiJlbmhhbmNlIGluZm8ifQ.nhPo3_dZOM2Sv1Ck7ryFLNCPbZRQUEKY7UB7wohts38&token_type=bearer&expires_in=3599&enhance=enhance%20info&jti=422d5416-3e95-42ad-9ca3-6bb3e010d648
            5、资源服务：带上access_token访问资源服务  http://localhost:8082/user/current?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE2MzY1NDI5MzAsImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6IjQyMmQ1NDE2LTNlOTUtNDJhZC05Y2EzLTZiYjNlMDEwZDY0OCIsImNsaWVudF9pZCI6ImNsaWVudCIsImVuaGFuY2UiOiJlbmhhbmNlIGluZm8ifQ.nhPo3_dZOM2Sv1Ck7ryFLNCPbZRQUEKY7UB7wohts38&token_type=bearer&expires_in=3599&enhance=enhance%20info&jti=422d5416-3e95-42ad-9ca3-6bb3e010d648
            注意：授权中心回调的URL，后面的PATH与access_token部分是用#（锚点）分隔的，这样access_token不会发到后端


            客户端模式：client_credentials  直接将令牌发给客户端，由客户端自行保存令牌，每次请求都需要带上令牌，适用于高度信任的内部服务之间API调用
            http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=oauth2-sso-client&client_secret=123456&scope=basic


            密码模式：password
            http://localhost:8080/oauth/token?username=tom&password=123456&grant_type=password&client_id=oauth2-sso-client&client_secret=123456&scope=basic


            刷新令牌：refresh_token
            http://localhost:8080/oauth/token?grant_type=refresh_token&client_id=oauth2-sso-client&client_secret=123456&refresh_token={refresh_token值}

         */

        // 以下配置，生产环境应该从数据库获取，sql参考：https://github.com/spring-projects/spring-security-oauth/blob/main/spring-security-oauth2/src/test/resources/schema.sql
        // clients.jdbc(datasource);
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        builder
                // 应用注册时生成的APP_ID
                .withClient("oauth2-sso-client")
                // 应用注册时生成的密码
                .secret(passwordEncoder.encode("123456"))
                // 应用注册时填写的回调地址，可以指定多个
                .redirectUris("http://localhost:8081/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400)
                .scopes("basic")
                .autoApprove(false)
                .authorizedGrantTypes("authorization_code", "implicit", "client_credentials", "password",
                        "refresh_token");
        builder
                // 应用注册时生成的APP_ID
                .withClient("resource-server")
                // 应用注册时生成的密码
                .secret(passwordEncoder.encode("123456"))
                // 应用注册时填写的回调地址，可以指定多个
                .redirectUris("http://localhost:8082/")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400)
                .scopes("avatar")
                .autoApprove(false)
                .authorizedGrantTypes("implicit", "client_credentials", "password", "refresh_token");
    }
}
